package com.jingyanzi.privilege.service.impl;

import java.util.ArrayList;
import java.util.Base64;
import java.util.Calendar;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.jingyanzi.finance.domain.CashCashierDO;
import com.jingyanzi.finance.factory.FinanceFactory;
import com.jingyanzi.privilege.dao.SecurityEmployeeMapper;
import com.jingyanzi.privilege.dao.SecurityJobsMapper;
import com.jingyanzi.privilege.dao.SecurityOrganizationMapper;

import com.jingyanzi.privilege.dao.SecurityPwdMapper;
import com.jingyanzi.privilege.dao.SecurityRoleMapper;
import com.jingyanzi.privilege.dao.SecurityRoleuserMapper;
import com.jingyanzi.privilege.dao.SecurityUserMapper;
import com.jingyanzi.privilege.domain.EmployeeDO;
import com.jingyanzi.privilege.domain.LoginDO;
import com.jingyanzi.privilege.domain.RoleDO;
import com.jingyanzi.privilege.domain.RoleUserDO;
import com.jingyanzi.privilege.domain.UserDO;
import com.jingyanzi.privilege.domain.result.ResultDO;
import com.jingyanzi.privilege.domain.result.ResultSupport;
import com.jingyanzi.privilege.entity.SecurityEmployee;
import com.jingyanzi.privilege.entity.SecurityEmployeeExample;
import com.jingyanzi.privilege.entity.SecurityEmployeeExample.Criteria;
import com.jingyanzi.privilege.entity.SecurityJobs;
import com.jingyanzi.privilege.entity.SecurityOrganization;
import com.jingyanzi.privilege.entity.SecurityOrganizationExample;
import com.jingyanzi.privilege.entity.SecurityPwd;
import com.jingyanzi.privilege.entity.SecurityPwdExample;
import com.jingyanzi.privilege.entity.SecurityRole;
import com.jingyanzi.privilege.entity.SecurityRoleuser;
import com.jingyanzi.privilege.entity.SecurityRoleuserExample;
import com.jingyanzi.privilege.entity.SecurityUser;
import com.jingyanzi.privilege.entity.SecurityUserExample;
import com.jingyanzi.privilege.query.EmployeeQueryDO;
import com.jingyanzi.privilege.query.UserQueryDO;
import com.jingyanzi.privilege.service.IRoleService;
import com.jingyanzi.privilege.service.IEmployeeService;
import com.jingyanzi.privilege.util.BeanUtilsExtends;
import com.jingyanzi.privilege.util.DESUtil;
import com.jingyanzi.privilege.util.PrivilegeConstant;
import com.jingyanzi.privilege.util.Tools;

@Service("employeeService")
public class EmployeeServiceImpl extends BaseServiceImpl implements IEmployeeService {

	private final Base64.Decoder decoder = Base64.getDecoder();

	private final Base64.Encoder encoder = Base64.getEncoder();

	@Autowired
	private SecurityUserMapper userMapper;

	@Autowired
	private SecurityPwdMapper pwdMapper;

	@Autowired
	private SecurityOrganizationMapper orgMapper;

	@Autowired
	private SecurityJobsMapper jobMapper;

	@Autowired
	private SecurityRoleMapper roleMapper;

	@Autowired
	private SecurityRoleuserMapper roleuserMapper;

	@Autowired
	private SecurityEmployeeMapper employeeMapper;
	
	@Autowired
	private SecurityOrganizationMapper organizationMapper;

	@Autowired
	private IRoleService roleService;

	public ResultDO verification(LoginDO loginDO) {

		ResultSupport result = new ResultSupport();

		SecurityUserExample example = new SecurityUserExample();
		
		SecurityPwdExample example1 = new SecurityPwdExample();

		List<SecurityUser> userList = new ArrayList<SecurityUser>();

		List<SecurityPwd> list = new ArrayList<SecurityPwd>();
		// 手机作为条件
		example.createCriteria().andMobileEqualTo(loginDO.getMobile()).andIsDeleteEqualTo(1);

		try {
			userList = userMapper.selectByExample(example);
		} catch (Exception e) {
			result.setErrorCode(ResultDO.USER_QUERY_ERROR);
			result.setErrorMsg("验证用户失败");
			result.setSuccess(false);
			return result;
		}

		// 通过手机查询出用户检测用户是否存在
		if (userList.size() == 0) {
			result.setErrorCode(ResultDO.EMPLOYEE_QUERY_ERROR);
			result.setErrorMsg("验证登陆失败员工没有登录用户信息");
			result.setSuccess(false);
			return result;
		}

		SecurityUser user = userList.get(0);

		// 密码作为条件
		example1.createCriteria().andMobileEqualTo(loginDO.getMobile()).andCodeEqualTo(loginDO.getPassword())
				.andStatusEqualTo(1);

		try {
			list = pwdMapper.selectByExample(example1);
		} catch (Exception e) {
			result.setErrorCode(ResultDO.USER_QUERY_ERROR);
			result.setErrorMsg("验证用户失败");
			result.setSuccess(false);
			return result;
		}

		// 判断密码是否有效
		if (list.size() == 0) {
			result.setErrorCode(ResultDO.USER_QUERY_ERROR);
			result.setErrorMsg("输入密码无效");
			result.setSuccess(false);
			return result;
		}

		SecurityPwd pwd = list.get(0);

		long expiryTime = pwd.getExpiryTime().getTime();
		long currentTime = System.currentTimeMillis();
		// 检查密码是否过期
		if (expiryTime < currentTime) {
			result.setErrorCode(ResultDO.USER_QUERY_ERROR);
			result.setErrorMsg("输入密码已经过期");
			result.setSuccess(false);
			return result;
		}

		int r = -1;
		// 设置密码已经使用
		pwd.setStatus(-1);

		try {
			r = pwdMapper.updateByPrimaryKeySelective(pwd);
		} catch (Exception e) {
			result.setErrorCode(ResultDO.USER_QUERY_ERROR);
			result.setErrorMsg("验证用户失败");
			result.setSuccess(false);
			return result;
		}

		if (r < 0) {
			result.setErrorCode(ResultDO.USER_QUERY_ERROR);
			result.setErrorMsg("验证用户失败");
			result.setSuccess(false);
			return result;
		}

		// 更新用户登录次数
		int count = user.getLoginCount();
		count++;
		user.setLoginCount(count);
		user.setLasttime(new Date());
		r = -1;

		try {
			r = userMapper.updateByPrimaryKeySelective(user);
		} catch (Exception e) {
			result.setErrorCode(ResultDO.USER_QUERY_ERROR);
			result.setErrorMsg("验证用户失败");
			result.setSuccess(false);
			return result;
		}

		if (r < 0) {
			result.setErrorCode(ResultDO.USER_QUERY_ERROR);
			result.setErrorMsg("验证用户失败");
			result.setSuccess(false);
			return result;
		}

		loginDO.setId(userList.get(0).getId());
		loginDO.setNickname(userList.get(0).getRealName());
		loginDO.setMobile(userList.get(0).getMobile());
		loginDO.setToken(getToken(userList.get(0)));
		// 返回用户ID
		result.setModel(ResultDO.FIRST_MODEL_KEY, loginDO);

		return result;
	}

	private String getToken(SecurityUser user) {
		String token = user.getId() + "-" + user.getMobile() + "-" + System.currentTimeMillis();
		return encoder.encodeToString(DESUtil.encryptMode(token.getBytes()));
	}

	public ResultDO checkToken(String token, long timestamp) {

		ResultSupport result = new ResultSupport();

		SecurityUserExample example = new SecurityUserExample();

		token = new String(decoder.decode(token));
		String[] values = token.split("-");
		// 手机作为条件
		example.createCriteria().andIdEqualTo(Integer.parseInt(values[0])).andMobileEqualTo(values[1])
				.andIsDeleteEqualTo(1);
		List<SecurityUser> userList = new ArrayList<SecurityUser>();
		try {
			userList = userMapper.selectByExample(example);
		} catch (Exception e) {
			result.setErrorCode(ResultDO.USER_QUERY_ERROR);
			result.setErrorMsg("验证令牌失败");
			result.setSuccess(false);
			return result;
		}

		// 通过手机查询出用户检测用户是否存在
		if (userList.size() == 0) {
			result.setSuccess(false);
			return result;
		}

		if ((System.currentTimeMillis() - timestamp) > 1800000) {
			result.setSuccess(false);
			return result;
		}

		return result;
	}

	public ResultDO generateVerification(String mobile) {

		ResultSupport result = new ResultSupport();

		SecurityUserExample example = new SecurityUserExample();
		SecurityPwd pwd = new SecurityPwd();

		example.createCriteria().andMobileEqualTo(mobile).andIsDeleteEqualTo(1);

		int count = 0;

		try {
			count = userMapper.countByExample(example);
		} catch (Exception e) {
			result.setErrorCode(ResultDO.USER_QUERY_ERROR);
			result.setErrorMsg("用户不存在获取密码失败");
			result.setSuccess(false);
			return result;
		}
		// 用户的手机号是否存在
		if (count == 0) {
			result.setErrorCode(ResultDO.USER_QUERY_ERROR);
			result.setErrorMsg("用户手机号吗不存在");
			result.setSuccess(false);
			return result;
		}

		String code = Tools.random();
		// 生成用户密码
		pwd.setCode(code);
		pwd.setMobile(mobile);
		pwd.setCreateTime(Calendar.getInstance().getTime());
		long timeMillis = Calendar.getInstance().getTime().getTime();
		// 设置超时时间为5分钟
		timeMillis = timeMillis + (5 * 60 * 1000);
		pwd.setExpiryTime(new Date(timeMillis));

		int r = -1;
		// 写入密码表
		try {
			r = pwdMapper.insertSelective(pwd);
		} catch (Exception e) {
			e.printStackTrace();
			result.setErrorCode(ResultDO.USER_QUERY_ERROR);
			result.setErrorMsg("生成密码失败");
			result.setSuccess(false);
			return result;
		}

		if (r < 0) {
			result.setErrorCode(ResultDO.USER_QUERY_ERROR);
			result.setErrorMsg("生成密码失败");
			result.setSuccess(false);
			return result;
		}

		result.setModel(ResultDO.FIRST_MODEL_KEY, code);

		return result;
	}

	public ResultDO register(EmployeeDO employeeDO) {

		SecurityEmployee employee = new SecurityEmployee();

		// 复制DO到Entity
		ResultSupport result = BeanUtilsExtends.copy(employee, employeeDO);

		// 判断复制是否成功
		if (!result.isSuccess())
			return result;
		
		SecurityJobs jobs = null;
		if(employeeDO.getJobsId() != null) {
			try {
				jobs = jobMapper.selectByPrimaryKey(employeeDO.getJobsId());
			} catch (Exception e) {
				result.setErrorCode(ResultDO.JOB_QUERY_ERROR);
				result.setErrorMsg("获取岗位数据失败");
				return result;
			}
	
			if (jobs == null) {
				result.setErrorCode(ResultDO.JOB_QUERY_ERROR);
				result.setErrorMsg("获取岗位数据失败");
				result.setSuccess(false);
				return result;
			}
			
			employee.setJobName(jobs.getName());
		}

		SecurityOrganization org = null;
		try {
			org = orgMapper.selectByPrimaryKey(employeeDO.getOrgId());
		} catch (Exception e) {
			result.setErrorCode(ResultDO.ORG_QUERY_ERROR);
			result.setErrorMsg("获取部门信息失败");
			result.setSuccess(false);
			return result;
		}

		if (org == null) {
			result.setErrorCode(ResultDO.ORG_QUERY_ERROR);
			result.setErrorMsg("获取部门信息失败");
			result.setSuccess(false);
			return result;
		}
		//employee.setCode(org.getCode());
		employee.setCreatetime(Calendar.getInstance().getTime());
		employee.setModifitime(employee.getCreatetime());
		employee.setIsDelete(1);
		employee.setStatus(1);
		employee.setIsUser(employeeDO.getIsUser());
		
		employee.setDepartment(org.getNameCode());

		int r = -1;

		try {
			r = employeeMapper.insertSelective(employee);
		} catch (Exception e) {
			e.printStackTrace();
			result.setErrorCode(ResultDO.EMPLOYEE_ADD_ERROR);
			result.setErrorMsg("员工注册失败");
			result.setSuccess(false);
			return result;
		}

		// 插入标志小于1时报错
		if (r < 1) {
			result.setErrorCode(ResultDO.EMPLOYEE_ADD_ERROR);
			result.setErrorMsg("员工注册失败");
			result.setSuccess(false);
			return result;
		}

		r = -1;
		// 如果机构下面有用户了就设置为是叶子节点
		org.setIsNode(1);
		try {
			r = orgMapper.updateByPrimaryKey(org);
		} catch (Exception e) {
			result.setErrorCode(ResultDO.EMPLOYEE_ADD_ERROR);
			result.setErrorMsg("员工注册失败");
			return result;
		}

		if (r < 1) {
			result.setErrorCode(ResultDO.EMPLOYEE_ADD_ERROR);
			result.setErrorMsg("员工注册失败");
			result.setSuccess(false);
			return result;
		}
		
		if(employee.getIsUser().intValue() == 1) {
		
			SecurityUser user = new SecurityUser();
			// 设置用户值
			user.setId(employee.getId());
			user.setRealName(employee.getRealName());
			user.setMobile(employee.getMobile());
			user.setPasscode(Tools.MD5(Tools.MD5(PrivilegeConstant.INIT_PASSCODE) + employee.getMobile()));
			user.setLoginCount(0);
			user.setFailCount(0);
			user.setStatus(1);
			user.setActivation(0);
			if (employeeDO.getIsUser().intValue() == 1) {
				user.setIsDelete(1);
			} else {
				user.setIsDelete(-1);
			}
			try {
				r = userMapper.insertSelective(user);
			} catch (Exception e) {
				e.printStackTrace();
				result.setErrorCode(ResultDO.EMPLOYEE_ADD_ERROR);
				result.setErrorMsg("员工注册失败");
				result.setSuccess(false);
				return result;
			}
	
			if (!setUserRole(user.getId(), employeeDO.getRoleIds())) {
				result.setErrorCode(ResultDO.EMPLOYEE_ADD_ERROR);
				result.setErrorMsg("设置用户的角色失败");
				result.setSuccess(false);
				return result;
			}
		}

		result.setModel(ResultDO.FIRST_MODEL_KEY, employee.getId());
		return result;
	}

	private boolean setUserRole(Integer userId, Integer[] roleIds) {

		for (Integer roleId : roleIds) {
			SecurityRoleuser userRole = new SecurityRoleuser();
			userRole.setUserId(userId);
			userRole.setRoleId(roleId);
			try {
				roleuserMapper.insert(userRole);
			} catch (Exception e) {
				e.printStackTrace();
				return false;
			}
		}

		return true;
	}

	public ResultDO modifi(EmployeeDO employeeDO) {

		SecurityEmployee employee = new SecurityEmployee();

		//复制DO到Entity
		ResultSupport result = BeanUtilsExtends.copy(employee, employeeDO);
		if (!result.isSuccess()) {
			result.setErrorCode(ResultDO.EMPLOYEE_EDIT_ERROR);
			result.setErrorMsg("对象转换失败");
			result.setSuccess(false);
			return result;
		}
		int c = -1;
		//删除用户映射
		c = removeMapping(employeeDO.getId());

		if (c < 1) {
			result.setErrorCode(ResultDO.EMPLOYEE_EDIT_ERROR);
			result.setErrorMsg("修改员工信息失败");
			result.setSuccess(false);
			return result;
		}

		SecurityJobs jobs = null;
		if(employeeDO.getJobsId() != null) {
			try {
				jobs = jobMapper.selectByPrimaryKey(employeeDO.getJobsId());
			} catch (Exception e) {
				result.setErrorCode(ResultDO.JOB_QUERY_ERROR);
				result.setErrorMsg("获取岗位数据失败");
				return result;
			}
	
			if (jobs == null) {
				result.setErrorCode(ResultDO.JOB_QUERY_ERROR);
				result.setErrorMsg("获取岗位数据失败");
				result.setSuccess(false);
				return result;
			}
			
			employee.setJobName(jobs.getName());
		}
		
		SecurityOrganization org = null;

		try {
			org = orgMapper.selectByPrimaryKey(employeeDO.getOrgId());
		} catch (Exception e) {
			result.setErrorCode(ResultDO.EMPLOYEE_EDIT_ERROR);
			result.setErrorMsg("获取部门信息失败");
			result.setSuccess(false);
			return result;
		}
		if (org == null) {
			result.setErrorCode(ResultDO.EMPLOYEE_EDIT_ERROR);
			result.setErrorMsg("获取部门信息失败");
			result.setSuccess(false);
			return result;
		}

		employee.setModifitime(Calendar.getInstance().getTime());
		
		employee.setDepartment(org.getNameCode());
		//employee.setCode(org.getCode());
		int r = -1;

		try {
			r = employeeMapper.updateByPrimaryKeySelective(employee);
		} catch (Exception e) {
			result.setErrorCode(ResultDO.EMPLOYEE_EDIT_ERROR);
			result.setErrorMsg("修改员工信息失败");
			result.setSuccess(false);
			return result;
		}

		// 插入标志小于1时报错
		if (r < 1) {
			result.setErrorCode(ResultDO.EMPLOYEE_EDIT_ERROR);
			result.setErrorMsg("修改员工信息失败");
			result.setSuccess(false);
			return result;
		}

		SecurityUser user = null;
		if (employeeDO.getIsUser() == 1) {
			
			try {
				user = userMapper.selectByPrimaryKey(employee.getId());
			} catch (Exception e) {
				e.printStackTrace();
				result.setErrorCode(ResultDO.EMPLOYEE_ADD_ERROR);
				result.setErrorMsg("员工注册失败");
				result.setSuccess(false);
				return result;
			}
			
			if(user == null) {
				user = new SecurityUser();
				// 设置用户值
				user.setId(employee.getId());
				user.setRealName(employee.getRealName());
				user.setMobile(employee.getMobile());
				user.setPasscode(Tools.MD5(Tools.MD5(PrivilegeConstant.INIT_PASSCODE) + employee.getMobile()));
				user.setLoginCount(0);
				user.setFailCount(0);
				user.setStatus(1);
				user.setActivation(0);
				if (employeeDO.getIsUser().intValue() == 1) {
					user.setIsDelete(1);
				} else {
					user.setIsDelete(-1);
				}
				try {
					r = userMapper.insertSelective(user);
				} catch (Exception e) {
					e.printStackTrace();
					result.setErrorCode(ResultDO.EMPLOYEE_ADD_ERROR);
					result.setErrorMsg("员工注册失败");
					result.setSuccess(false);
					return result;
				}
	
				if (!setUserRole(user.getId(), employeeDO.getRoleIds())) {
					result.setErrorCode(ResultDO.EMPLOYEE_ADD_ERROR);
					result.setErrorMsg("设置用户的角色失败");
					result.setSuccess(false);
					return result;
				}
			} else {
				r = -1;
				// 设置用户值
				user.setId(employee.getId());
				user.setIsDelete(1);
				try {
					r = userMapper.updateByPrimaryKeySelective(user);
				} catch (Exception e) {
					result.setErrorCode(ResultDO.EMPLOYEE_EDIT_ERROR);
					result.setErrorMsg("打开员工用户失败");
					result.setSuccess(false);
					return result;
				}
				
				if(r < 0) {
					result.setErrorCode(ResultDO.EMPLOYEE_EDIT_ERROR);
					result.setErrorMsg("打开员工用户失败");
					result.setSuccess(false);
					return result;
				}
				
				if (!setUserRole(user.getId(), employeeDO.getRoleIds())) {
					result.setErrorCode(ResultDO.EMPLOYEE_ADD_ERROR);
					result.setErrorMsg("设置用户的角色失败");
					result.setSuccess(false);
					return result;
				}
			}
			
		} else {
			user = new SecurityUser();
			r = -1;
			// 删除用户映射
			r = removeMapping(employee.getId());
			// 设置用户值
			user.setId(employee.getId());
			user.setIsDelete(-1);
			try {
				r = userMapper.updateByPrimaryKeySelective(user);
			} catch (Exception e) {
				result.setErrorCode(ResultDO.EMPLOYEE_EDIT_ERROR);
				result.setErrorMsg("删除员工用户失败");
				result.setSuccess(false);
				return result;
			}
			
			if(r < 0) {
				result.setErrorCode(ResultDO.EMPLOYEE_EDIT_ERROR);
				result.setErrorMsg("删除员工用户失败");
				result.setSuccess(false);
				return result;
			}
		}

		return result;
	}
	
	
	public ResultDO addUser(UserDO domain) {
	
		SecurityUser entity = new SecurityUser();
		// 复制DO到Entity
		ResultSupport result = BeanUtilsExtends.copy(entity, domain);
		
		if(!result.isSuccess()) {
			result.setErrorCode(ResultDO.USER_ADD_ERROR);
			result.setErrorMsg("对象转换失败");
			result.setSuccess(false);
			return result;
		}
		//设置用户初始密码
		String passcode = Tools.MD5(Tools.MD5(PrivilegeConstant.INIT_PASSCODE) + domain.getMobile());
		
		int id = UUID.randomUUID().hashCode();
		entity.setId(Math.abs(id));
		entity.setPasscode(passcode);
		entity.setIsDelete(1);
		entity.setStatus(PrivilegeConstant.OTHER_USER_ACCOUNT);
		entity.setLoginCount(0);
		//用户为未激活状态
		entity.setActivation(PrivilegeConstant.ACTIVATION_NOT_USER);
		entity.setFailCount(0);
		int r = -1;
		
		try {
			r = userMapper.insertSelective(entity);
		} catch (Exception e) {
			e.printStackTrace();
			r = -1;
		}

		if(r < 0) {
			result.setErrorCode(ResultDO.USER_ADD_ERROR);
			result.setErrorMsg("添加用户失败");
			result.setSuccess(false);
			return result;
		}
		
		if (!setUserRole(entity.getId(), domain.getRoleIds())) {
			result.setErrorCode(ResultDO.USER_ADD_ERROR);
			result.setErrorMsg("添加用户角色关联失败");
			result.setSuccess(false);
			return result;
		}
		
		result.setModel(ResultSupport.FIRST_MODEL_KEY, entity.getId());
		return result;
	}

	/**
	 * 开通员工登录
	 * 
	 * @param UserDO
	 *            userDO
	 * 
	 * @return
	 */
	public ResultDO openLogin(UserDO userDO) {

		ResultSupport result = new ResultSupport();

		SecurityUser user = new SecurityUser();

		SecurityEmployee employee = new SecurityEmployee();

		int r = -1;

		r = -1;
		employee.setId(userDO.getId());
		employee.setIsUser(1);
		try {
			// 更新员工开通用户
			r = employeeMapper.updateByPrimaryKeySelective(employee);
		} catch (Exception e) {
			result.setErrorCode(ResultDO.USER_EDIT_ERROR);
			result.setErrorMsg("开通登录帐户失败");
			result.setSuccess(false);
			return result;
		}

		if (r < 1) {
			result.setErrorCode(ResultDO.USER_EDIT_ERROR);
			result.setErrorMsg("开通登录帐户失败");
			result.setSuccess(false);
			return result;
		}
		// 设置员工权限有效
		user.setIsDelete(1);
		user.setId(userDO.getId());
		try {
			r = userMapper.updateByPrimaryKeySelective(user);
		} catch (Exception e) {
			result.setErrorCode(ResultDO.USER_EDIT_ERROR);
			result.setErrorMsg("开通登录帐户失败");
			result.setSuccess(false);
			return result;
		}

		if (r < 1) {
			result.setErrorCode(ResultDO.USER_EDIT_ERROR);
			result.setErrorMsg("开通登录帐户失败");
			result.setSuccess(false);
			return result;
		}

		// 设置用户角色
		
		if (!setUserRole(userDO.getId(), userDO.getRoleIds())) {
			result.setErrorCode(ResultDO.USER_EDIT_ERROR);
			result.setErrorMsg("开通登录帐户设置角色失败");
			result.setSuccess(false);
			return result;
		}

		result.setModel(ResultDO.FIRST_MODEL_KEY, user.getId());
		return result;
	}

	public ResultDO userDeleteOrClose(Integer id) {
		
		ResultSupport result = new ResultSupport();
		SecurityUser user = null;
		
		try {
			user = userMapper.selectByPrimaryKey(id);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		if(user.getStatus() == 0) {
			ResultDO res = this.removeUser(id);
			if(!res.isSuccess()) {
				return res;
			}
		} else {
			ResultDO res = this.closeUser(id);
			if(!res.isSuccess()) {
				return res;
			}
		}
		
		return result;
	}
	public ResultDO remove(Integer id) {

		ResultSupport result = new ResultSupport();

		SecurityUser user = new SecurityUser();

		SecurityEmployee employee = new SecurityEmployee();
		// 设置用户删除
		user.setId(id);
		user.setIsDelete(-1);
		// 设置员工删除
		employee.setId(id);
		employee.setIsDelete(-1);

		int r = -1;
		// 删除用户映射
		r = removeMapping(id);

		if (r < 1) {
			result.setErrorCode(ResultDO.EMPLOYEE_DELETE_ERROR);
			result.setErrorMsg("删除用户映射失败");
			result.setSuccess(false);
			return result;
		}

		try {
			r = -1;
			SecurityUser securityUser = userMapper.selectByPrimaryKey(id);
			if (securityUser != null) {
				r = userMapper.updateByPrimaryKeySelective(user);
				if (r < 1) {
					result.setSuccess(false);
				}
			}

		} catch (Exception e) {
			e.printStackTrace();
			result.setErrorCode(ResultDO.EMPLOYEE_DELETE_ERROR);
			result.setErrorMsg("删除用户失败");
			result.setSuccess(false);
			return result;
		}

		try {
			r = -1;
			r = employeeMapper.updateByPrimaryKeySelective(employee);
		} catch (Exception e) {
			e.printStackTrace();
			result.setErrorCode(ResultDO.EMPLOYEE_DELETE_ERROR);
			result.setErrorMsg("删除员工信息失败");
			result.setSuccess(false);
			return result;
		}

		if (r < 1) {
			result.setErrorCode(ResultDO.EMPLOYEE_DELETE_ERROR);
			result.setErrorMsg("删除员工信息失败");
			result.setSuccess(false);
			return result;
		}

		return result;
	}
	
	public ResultDO removeUser(Integer id) {

		ResultSupport result = new ResultSupport();

		SecurityUser user = new SecurityUser();

		// 设置用户删除
		user.setId(id);
		user.setIsDelete(-1);
	
		int r = -1;
		// 删除用户映射
		r = removeMapping(id);

		if (r < 1) {
			result.setErrorCode(ResultDO.USER_DELETE_ERROR);
			result.setErrorMsg("删除用户映射失败");
			result.setSuccess(false);
			return result;
		}

		try {
			r = -1;
			SecurityUser securityUser = userMapper.selectByPrimaryKey(id);
			if (securityUser != null) {
				r = userMapper.updateByPrimaryKeySelective(user);
				if (r < 1) {
					result.setSuccess(false);
				}
			}

		} catch (Exception e) {
			e.printStackTrace();
			result.setErrorCode(ResultDO.USER_DELETE_ERROR);
			result.setErrorMsg("删除用户失败");
			result.setSuccess(false);
			return result;
		}
		
		return result;
	}

	public ResultDO closeUser(Integer id) {

		ResultSupport result = new ResultSupport();

		SecurityUser user = new SecurityUser();

		SecurityEmployee employee = new SecurityEmployee();

		user.setId(id);
	
		user.setIsDelete(-1);
		int r = -1;
		// 删除用户映射
		r = removeMapping(id);

		if (r < 1) {
			result.setErrorCode(ResultDO.USER_DELETE_ERROR);
			result.setErrorMsg("删除用户映射失败");
			result.setSuccess(false);
			return result;
		}
		try {
			r = -1;
			r = userMapper.updateByPrimaryKeySelective(user);
		} catch (Exception e) {
			e.printStackTrace();
			result.setErrorCode(ResultDO.USER_DELETE_ERROR);
			result.setErrorMsg("关闭用户失败");
			result.setSuccess(false);
			return result;
		}

		if (r < 1) {
			result.setErrorCode(ResultDO.USER_DELETE_ERROR);
			result.setErrorMsg("关闭用户失败");
			result.setSuccess(false);
			return result;
		}

		employee.setId(id);
		employee.setIsUser(0);
		try {
			// 更新员工开通用户
			r = employeeMapper.updateByPrimaryKeySelective(employee);
		} catch (Exception e) {
			e.printStackTrace();
			result.setErrorCode(ResultDO.USER_DELETE_ERROR);
			result.setErrorMsg("更新员工关闭用户失败");
			result.setSuccess(false);
			return result;
		}

		if (r < 1) {
			result.setErrorCode(ResultDO.USER_DELETE_ERROR);
			result.setErrorMsg("更新员工关闭用户失败");
			result.setSuccess(false);
			return result;
		}

		return result;
	}

	public ResultDO updateRole(UserDO userDO) {

		ResultSupport result = new ResultSupport();

		int r = -1;
		// 删除用户映射
		r = removeMapping(userDO.getId());

		if (r < 1) {
			result.setErrorCode(ResultDO.USER_EDIT_ERROR);
			result.setErrorMsg("删除用户映射失败");
			result.setSuccess(false);
			return result;
		}

		r = -1;
		if (userDO.getRoleIds() == null || userDO.getRoleIds().length == 0) {
			result.setErrorCode(ResultDO.USER_EDIT_ERROR);
			result.setErrorMsg("更新用户的角色失败");
			result.setSuccess(false);
			return result;
		}

		

		if (!setUserRole(userDO.getId(), userDO.getRoleIds())) {
			result.setErrorCode(ResultDO.USER_EDIT_ERROR);
			result.setErrorMsg("更新用户的角色失败");
			result.setSuccess(false);
			return result;
		}

		return result;
	}

	public ResultDO getUser(Integer id) {

		ResultSupport result = new ResultSupport();

		if (id < 1) {
			result.setSuccess(false);
			return result;
		}

		SecurityUser user = null;

		try {
			user = userMapper.selectByPrimaryKey(id);
		} catch (Exception e) {
			e.printStackTrace();
		}

		if (user == null) {
			result.setSuccess(false);
			return result;
		}

		UserDO userDO = getUserDO(user);

		SecurityRoleuserExample example1 = new SecurityRoleuserExample();
		// 返回用户的角色
		example1.createCriteria().andUserIdEqualTo(user.getId());

		List<SecurityRoleuser> list = null;
		// 返回用户对应的所有角色
		try {
			list = roleuserMapper.selectByExample(example1);
		} catch (Exception e) {
			e.printStackTrace();
		}

		List<RoleDO> roleDOList = new ArrayList<RoleDO>();

		for (SecurityRoleuser roleuser : list) {
			ResultDO resultDO = roleService.get(roleuser.getRoleId());

			if (!resultDO.isSuccess()) {
				result.setSuccess(false);
				return result;
			}
			roleDOList.add((RoleDO) resultDO.getModel(ResultSupport.FIRST_MODEL_KEY));
		}

		userDO.setRoleDOList(roleDOList);

		result.setModel(ResultSupport.FIRST_MODEL_KEY, userDO);
		return result;
	}

	public ResultDO getEmployee(Integer id) {

		ResultSupport result = new ResultSupport();

		SecurityEmployee employee = null;

		if (id < 1) {
			result.setSuccess(false);
			return result;
		}

		try {
			employee = employeeMapper.selectByPrimaryKey(id);
		} catch (Exception e) {
			e.printStackTrace();
		}

		if (employee == null) {
			result.setSuccess(false);
			return result;
		}

		EmployeeDO employeeDO = getEmployeeDO(employee);

		result.setModel(ResultSupport.FIRST_MODEL_KEY, employeeDO);

		return result;
	}


	public ResultDO queryEmployee(EmployeeQueryDO query) {

		ResultSupport result = new ResultSupport();

		List<SecurityEmployee> list = null;

		SecurityEmployeeExample example = new SecurityEmployeeExample();
		Criteria createCriteria = example.createCriteria();

		if (StringUtils.isNotEmpty(query.getNameOrTel())) {
			if (BeanUtilsExtends.isChinaPhoneLegal(query.getNameOrTel())) {
				createCriteria.andMobileLike("%" + query.getNameOrTel() + "%");
			} else {
				createCriteria.andRealNameLike("%" + query.getNameOrTel() + "%");
			}
		}
		
		if(StringUtils.isNotEmpty(query.getRealName())) {
			createCriteria.andRealNameEqualTo(query.getRealName());
		}
		
		if(!isNumberInValid(query.getOrgId())) {
			createCriteria.andOrgIdEqualTo(query.getOrgId());
		}
		
		if(!isNumberInValid(query.getJobsId())) {
			createCriteria.andJobsIdEqualTo(query.getJobsId());
		}
		
		// 非删除对象
		createCriteria.andIsDeleteEqualTo(1);

		List<EmployeeDO> employeeDOList = null;
		example.setOrderByClause("sortNum asc");
		// 是否进行分页
		if (query.isPage()) {
			example.setLimitByPage(query.getStart() + "," + query.getPageRows());
			long count = employeeMapper.countByExample(example);
			result.setModel(ResultSupport.SECOND_MODEL_KEY, count);
		}
		
		
		try {
			list = employeeMapper.selectByExample(example);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		
		employeeDOList = getEmployeeDOList(list);
		
		for(EmployeeDO employeeDO : employeeDOList) {
			if(query.getCheckCashier().intValue() == 1) {
				com.jingyanzi.finance.result.ResultDO res = FinanceFactory.getICashierService().isEmployeeCashier(employeeDO.getId());
				if(!res.isSuccess()) {
					result.setSuccess(false);
					return result;
				}
				CashCashierDO cashCashierDO = (CashCashierDO) res.getModel(ResultSupport.FIRST_MODEL_KEY);
				if(cashCashierDO != null) {
					employeeDO.setCashierId(cashCashierDO.getId());
					employeeDO.setIsCashier(1);
				} else {
					employeeDO.setCashierId(0);
					employeeDO.setIsCashier(0);
				}
			}
		}
		result.setModel(ResultSupport.FIRST_MODEL_KEY, employeeDOList);

		return result;
	}
	
	
	public ResultDO queryEmployeeByCode(EmployeeQueryDO query) {

		ResultSupport result = new ResultSupport();

		SecurityOrganizationExample example1 = new SecurityOrganizationExample();
		
		if (StringUtils.isNotBlank(query.getCode())) {
			example1.createCriteria().andCodeLike(query.getCode() + "%").andIsDeleteEqualTo(1);
		}
		List<SecurityOrganization> orgList = null;
		try {
			orgList = organizationMapper.selectByExample(example1);
		} catch (Exception e) {
			e.printStackTrace();
			result.setErrorMsg("获取岗位信息失败");
			result.setSuccess(false);
			return result;
		}

		List<Integer> orgIds = new ArrayList<Integer>();
		for(SecurityOrganization org : orgList) {
			orgIds.add(org.getId());
		}
		List<SecurityEmployee> list = null;

		SecurityEmployeeExample example = new SecurityEmployeeExample();
		Criteria createCriteria = example.createCriteria();
		if(orgIds.size() != 0) {
			//createCriteria.andIdEqualTo(org.getId()).andIsDeleteEqualTo(1);
			createCriteria.andOrgIdIn(orgIds).andIsDeleteEqualTo(1);
		}
		if (query.getNameOrTel() != null) {
			if (BeanUtilsExtends.isChinaPhoneLegal(query.getNameOrTel())) {
				createCriteria.andMobileLike("%" + query.getNameOrTel() + "%");
			} else {
				createCriteria.andRealNameLike("%" + query.getNameOrTel() + "%");
			}
		}
		if(query.getJobsId() != 0) {
			createCriteria.andJobsIdEqualTo(query.getJobsId());
		}
		// 是否进行分页
		if (query.isPage()) {
			example.setLimitByPage(query.getStart() + "," + query.getPageRows());
			long count = employeeMapper.countByExample(example);
			result.setModel(ResultSupport.SECOND_MODEL_KEY, count);
		}
		
		try {
			list = employeeMapper.selectByExample(example);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		List<EmployeeDO> listDO = getEmployeeDOList(list);
		
		for(EmployeeDO employeeDO : listDO) {
			employeeDO.setCode(query.getCode());
		}
	
		for(EmployeeDO employeeDO : listDO) {
			if(query.getCheckCashier().intValue() == 1) {
				System.out.println(employeeDO.getRealName());
				com.jingyanzi.finance.result.ResultDO res = FinanceFactory.getICashierService().isEmployeeCashier(employeeDO.getId());
				if(!res.isSuccess()) {
					result.setSuccess(false);
					return result;
				}
				CashCashierDO cashCashierDO = (CashCashierDO) res.getModel(ResultSupport.FIRST_MODEL_KEY);
				if(cashCashierDO != null) {
					employeeDO.setCashierId(cashCashierDO.getId());
					employeeDO.setIsCashier(1);
				} else {
					employeeDO.setCashierId(0);
					employeeDO.setIsCashier(0);
				}
			}
		}
		result.setModel(ResultSupport.FIRST_MODEL_KEY, listDO.stream().sorted(Comparator.comparing(EmployeeDO::getSortNum)).collect(Collectors.toList()));

		return result;
	}

	public ResultDO getRole(Integer id) {

		ResultSupport result = new ResultSupport();

		List<SecurityRoleuser> list = null;

		SecurityRoleuserExample example = new SecurityRoleuserExample();
		if (id != 0) {
			example.createCriteria().andUserIdEqualTo(id);
		}
		List<RoleUserDO> userDOList = null;
		try {
			list = roleuserMapper.selectByExample(example);
		} catch (Exception e) {
			e.printStackTrace();
		}

		userDOList = getRoleUserList(list);

		result.setModel(ResultSupport.FIRST_MODEL_KEY, userDOList);

		return result;
	}

	public ResultDO queryUser(UserQueryDO query) {

		ResultSupport result = new ResultSupport();

		List<SecurityUser> list = null;

		SecurityUserExample example = new SecurityUserExample();
		com.jingyanzi.privilege.entity.SecurityUserExample.Criteria createCriteria = example.createCriteria();
		
		
		if (query.getNameOrTel() != null) {
			if (BeanUtilsExtends.isChinaPhoneLegal(query.getNameOrTel())) {
				createCriteria.andMobileLike("%" + query.getNameOrTel() + "%");
			} else {
				createCriteria.andRealNameLike("%" + query.getNameOrTel() + "%");
			}
		}
		
		if (StringUtils.isNotBlank(query.getMobile())) {
			createCriteria.andMobileEqualTo(query.getMobile());
		}

	
		if (StringUtils.isNotBlank(query.getRealName())) {
			createCriteria.andRealNameLike("%" + query.getRealName() + "%");
		}
		
		if (query.getId() != 0) {
			createCriteria.andIdEqualTo(query.getId());
		}
		// 非删除对象
		createCriteria.andIsDeleteEqualTo(1);

		List<UserDO> userDOList = null;

		if (query.isPage()) {
			example.setLimitByPage(query.getStart() + "," + query.getPageRows());
			long count = userMapper.countByExample(example);
			result.setModel(ResultSupport.SECOND_MODEL_KEY, count);
		}
		
		try {
			list = userMapper.selectByExample(example);
		} catch (Exception e) {
			e.printStackTrace();
		}

		userDOList = getUserDOList(list);

		for (UserDO userDO : userDOList) {

			SecurityRoleuserExample example1 = new SecurityRoleuserExample();
			// 返回用户的角色
			example1.createCriteria().andUserIdEqualTo(userDO.getId());

			List<SecurityRoleuser> list2 = null;
			// 返回用户对应的所有角色
			try {
				list2 = roleuserMapper.selectByExample(example1);
			} catch (Exception e) {
				e.printStackTrace();
			}

			List<RoleDO> roleDOList = new ArrayList<RoleDO>();

			for (SecurityRoleuser roleuser : list2) {
				// 返回角色
				SecurityRole role = null;
				try {
					role = roleMapper.selectByPrimaryKey(roleuser.getRoleId());
				} catch (Exception e) {
					result.setSuccess(false);
					return result;
				}
				// 加入角色列表
				roleDOList.add(getRoleDO(role));
			}
			// 角色加入用户
			userDO.setRoleDOList(roleDOList);
		}

		result.setModel(ResultSupport.FIRST_MODEL_KEY, userDOList);

		return result;
	}

	private int removeMapping(int id) {

		SecurityRoleuserExample example1 = new SecurityRoleuserExample();

		example1.createCriteria().andUserIdEqualTo(id);

		int r = -1;

		try {
			r = roleuserMapper.deleteByExample(example1);
		} catch (Exception e) {
			return -1;
		}

		if (r < -1) {
			return -1;
		}

		return 1;
	}

	@Override
	public ResultDO modifiPassCode(UserDO domain) {
		
		ResultSupport result = new ResultSupport();
		
		ResultDO res = checkUser(domain);
		
		if(!res.isSuccess()) {
			return res;
		}
				
		SecurityUser user = (SecurityUser) res.getModel(ResultDO.FIRST_MODEL_KEY);
	
		String passcode = Tools.MD5(domain.getPassword() + domain.getMobile());
		
		
		//用户是否激活
		if(user.getActivation() == 0) {
			//未激活时设置两次MD5加密
			user.setActivation(1);
		} 
		
		user.setPasscode(passcode);
		//更新用户密码
		int r = -1;
		
		try {
			r = userMapper.updateByPrimaryKey(user);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		if(r < 0) {
			result.setSuccess(false);
			result.setErrorCode(ResultDO.USER_EDIT_ERROR);
			result.setErrorMsg("用户修改密码失败");
			return result;
		}
		
		return result;
	}
	
	
	private ResultDO checkUser(UserDO domain) {
		
		ResultSupport result = new ResultSupport();
		
		SecurityUserExample example = new SecurityUserExample();
		
		example.createCriteria().andMobileEqualTo(domain.getMobile()).andIsDeleteEqualTo(1);

		List<SecurityUser> list = null;
		try {
			list = userMapper.selectByExample(example);
		} catch (Exception e) {
			e.printStackTrace();
		}
		//检查用户是否存在
		if(list.size() == 0) {
			result.setSuccess(false);
			result.setErrorCode(ResultDO.USER_QUERY_ERROR);
			result.setErrorMsg("用户账户不存在");
			return result;
		}
		
		SecurityUser user = list.get(0);
		
		if(user.getFailCount() > 100) {
			//这里可以设置锁定的代码现在暂时不用
		}
	
		String oldpasscode = Tools.MD5(domain.getOldPassword().toUpperCase() + domain.getMobile());
		
		SecurityUserExample example2 = new SecurityUserExample();
		
		example2.createCriteria().andIdEqualTo(user.getId()).andPasscodeEqualTo(oldpasscode).andIsDeleteEqualTo(1);
		
		int count = 0;
		try {
			count = userMapper.countByExample(example2);
		} catch (Exception e) {
			e.printStackTrace();
		}
		//判断用户旧密码是否有效
		if(count == 0) {
			/*
			// 更新用户登录次数
			int failCount = user.getFailCount();
			failCount++;
			user.setFailCount(failCount);
			//更新用户状态
			try {
				userMapper.updateByPrimaryKeySelective(user);
			} catch (Exception e) {
				e.printStackTrace();
			}
			
			*/
			result.setSuccess(false);
			result.setErrorCode(ResultDO.USER_QUERY_ERROR);
			result.setErrorMsg("用户密码错误");
			return result;
		}
		
		result.setModel(ResultSupport.FIRST_MODEL_KEY, user);
		return result;
	}

	@Override
	public ResultDO userLogin(LoginDO domain) {
		
		ResultSupport result = new ResultSupport();
		
		UserDO userDO = new UserDO();
		userDO.setMobile(domain.getMobile());
		userDO.setOldPassword(domain.getPassword());
		//检测用户账户信息
		ResultDO res = checkUser(userDO);
		
		if(!res.isSuccess()) {
			return res;
		}
		
		SecurityUser user = (SecurityUser) res.getModel(ResultDO.FIRST_MODEL_KEY);
		
		// 更新用户登录次数
		int count = user.getLoginCount();
		count++;
		user.setLoginCount(count);
		user.setLasttime(new Date());
		
		//更新用户状态
		try {
			userMapper.updateByPrimaryKeySelective(user);
		} catch (Exception e) {
			e.printStackTrace();
		}

		domain.setId(user.getId());
		domain.setNickname(user.getRealName());
		domain.setMobile(user.getMobile());
		domain.setToken(getToken(user));
		domain.setPassword(null);
		domain.setActivation(user.getActivation());
		// 返回用户登陆DO
		result.setModel(ResultDO.FIRST_MODEL_KEY, domain);
		
		return result;
	}

	@Override
	public ResultDO checkRepeat(UserDO domain) {
		
		ResultSupport result = new ResultSupport();
		
		SecurityUserExample example = new SecurityUserExample();
		
		int count = 0;
		if(domain.getId() == null) {
			example.createCriteria().andMobileEqualTo(domain.getMobile()).andIsDeleteEqualTo(1);
			try {
				count = userMapper.countByExample(example);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		result.setModel(ResultSupport.FIRST_MODEL_KEY, count);
		return result;
	}
	
	
	@Override
	public ResultDO checkEmployeeRepeat(EmployeeDO domain) {
		
		ResultSupport result = new ResultSupport();
		
		SecurityEmployeeExample example = new SecurityEmployeeExample();
		
		int count = 0;
		if(domain.getId() == null) {
			example.createCriteria().andMobileEqualTo(domain.getMobile()).andIsDeleteEqualTo(1);
		} else {
			example.createCriteria().andIdNotEqualTo(domain.getId()).andMobileEqualTo(domain.getMobile()).andIsDeleteEqualTo(1);
		}
		try {
			count = employeeMapper.countByExample(example);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		result.setModel(ResultSupport.FIRST_MODEL_KEY, count);
		return result;
	}

	@Override
	public ResultDO modifUser(UserDO domain) {
		
		SecurityUser entity = new SecurityUser();
		// 复制DO到Entity
		ResultSupport result = new ResultSupport();
		
		try {
			entity = userMapper.selectByPrimaryKey(domain.getId());
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		entity.setRealName(domain.getRealName());
	
		int r = -1;
		try {
			r = userMapper.updateByPrimaryKey(entity);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		if(r < 0) {
			result.setSuccess(false);
			result.setErrorCode(ResultDO.USER_EDIT_ERROR);
			result.setErrorMsg("用户修改失败");
			return result;
		}
		
		r = -1;
		// 删除用户映射
		r = removeMapping(domain.getId());

		if (r < 1) {
			result.setErrorCode(ResultDO.USER_EDIT_ERROR);
			result.setErrorMsg("删除用户映射失败");
			result.setSuccess(false);
			return result;
		}

		r = -1;
		if (domain.getRoleIds() == null || domain.getRoleIds().length == 0) {
			result.setErrorCode(ResultDO.USER_EDIT_ERROR);
			result.setErrorMsg("设置用户角色错误");
			result.setSuccess(false);
			return result;
		}

		if (!setUserRole(domain.getId(), domain.getRoleIds())) {
			result.setErrorCode(ResultDO.USER_EDIT_ERROR);
			result.setErrorMsg("更新员工开通用户失败");
			result.setSuccess(false);
			return result;
		}

		
		return result;
	}

	@Override
	public ResultDO restPassword(UserDO domain) {
		
		SecurityUser entity = new SecurityUser();
		// 复制DO到Entity
		ResultSupport result = new ResultSupport();
		
		
		try {
			entity = userMapper.selectByPrimaryKey(domain.getId());
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		//设置用户初始密码
		String passcode = Tools.MD5(Tools.MD5(PrivilegeConstant.INIT_PASSCODE) + entity.getMobile());
		
		entity.setPasscode(passcode);
		entity.setActivation(0);
		
		int r = -1;
		try {
			r = userMapper.updateByPrimaryKey(entity);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		if(r < 0) {
			result.setSuccess(false);
			result.setErrorCode(ResultDO.USER_EDIT_ERROR);
			result.setErrorMsg("重置用户失败");
			return result;
		}
		
		return result;
	}

}
